package com.qingke.stockdata.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.qingke.stockdata.mappers.UserMapper;
import com.qingke.stockdata.model.Stock;
import com.qingke.stockdata.model.StockData;
import com.qingke.stockdata.model.StockResult;
import com.qingke.stockdata.model.User;
import com.qingke.stockdata.service.StockService;

@Controller
public class HomeController {
	
	@Autowired
	private StockService stockService;
	
	@Autowired
	private UserMapper userMapper;
	
	@RequestMapping("/index")
	public String index(String username,Model model) {//登录后取出保存的username
		User user = null;
		try {
			user = userMapper.getUserByUsername(username);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Stock> stocks = stockService.selectAllStock(2);
		model.addAttribute("allstocks", stocks);
		return "index";
	}

	@RequestMapping(value = "/detail", method = RequestMethod.GET)
	public String add(String code, Model model) {
		StockResult result = stockService.addStock(code);
		Stock stock = result.getStock();
		List<StockData> stockDatas = result.getStockDatas();
		if (stockDatas != null) {
			List<StockData> datas = stockDatas.subList(0, 10);
			model.addAttribute("stockdata", datas);
			model.addAttribute("stock", stock);
		}
		if ("恭喜您，股票添加成功！".equals(result.getState())) {
			// 另一个线程运行计算最最高价格和最低价格并将网络数据全部插入数据库（耗时操作）
			final Stock stockCopy = stock;
			final List<StockData> stockDatasCopy = stockDatas;
			final int id = 2;// 获得当前用户的id
			new Thread(new Runnable() {
				public void run() {
					stockService.insertData(stockCopy,stockDatasCopy,id);
				}
			}).start();
			model.addAttribute("state", result.getState());
		}
		return "detail";
	}
}
